<template>
    <el-card shadow="never" class="card-border-none">
        <template #header>
            <div class="card-header">
                <span class="card-header-span">订单统计</span>
                <div>
                    <el-check-tag :checked="current == item.value" style="margin-right: 8px" v-for="(item,index) in options" :key="index" @click="handleChoose(item.value)">{{ item.text }}</el-check-tag>
                </div>
            </div>
        </template>
        <div id="chart" style="width: 100%;height: 300px"></div>
  </el-card>
</template>
<script setup>
import * as echarts from 'echarts';
import { ref,onMounted,onBeforeUnmount, onUnmounted  } from 'vue'
import { getStatistics3 } from '~/api/index.js'
// 图表根据div大小自适应插件
import elementResizeDetectorMaker from 'element-resize-detector'

// 初始化插件实例
const erd = elementResizeDetectorMaker();

const current = ref("week")
const options = ref([{
    text: "近1个月",
    value: "month"
}, {
    text: "近1周",
    value: "week"
}, {
    text: "近24小时",
    value:"hour"
}])

let myChart = null

onMounted(()=>{
    // 初始化图表
    myChart = echarts.init(document.getElementById('chart'));
    // 获取数据
    getData(current.value)

    // 监听图表所在div，实现根据div大小自适应
    erd.listenTo(document.getElementById("chart"), function () {
        myChart.resize()
    });
})

// 释放echarts对象，非常重要，没有释放的话，打包之后会出现白屏现象
onBeforeUnmount(()=>{
    if (myChart) {
        echarts.dispose(myChart)
    }
})

onUnmounted(() => {
    // 页面切换销毁插件
    erd.uninstall(document.getElementById("chart"))
})

// 图标配置项
let chartData = {
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: [{
        type: 'value'
    }],
    series: [{
        data:[],
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
        }
    }]
}

// 获取图表数据
function getData(type = "month"){
    myChart.showLoading();

    getStatistics3(type).then(res=>{
        chartData.xAxis.data = res.x
        chartData.series[0].data = res.y
        myChart.setOption(chartData)
    }).finally(()=>myChart.hideLoading())
}

// 图表大小随屏幕变化
function handleWindowResize(){
    myChart.resize()
}

// 选择日期并获取图表数据
const handleChoose = (v)=> {
    current.value = v
    getData(v)
}
</script>
<style lang="scss" scoped>
.card-border-none {
    border: none;
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .card-header-span {
            font-size: 14px;
        }
    }
}
</style>